<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/10/18
 * Time: 14:36
 * 档案类
 */
require_once(APPPATH . 'third_party/file/FileUtil.php');
//require_once(APPPATH . 'third_party/pdfmerge/Jurosh/PDFMerge/PDFMerger.php');
require_once(APPPATH . 'third_party/pdfmerge/Jurosh/PDFMerge/PDFObject.php');
require_once(APPPATH . 'third_party/pdf/fpdf/fpdf.php');
require_once(APPPATH . 'third_party/pdf/fpdi/fpdi.php');
class Archive extends Admin_Controller{
	public function __construct(){
		parent::__construct();
		$this->load->model("archive_model");
		$this->load->model("notary_matter_model");
		$this->load->model("category_model");
		$this->load->model("archive_applicant_model");
		$this->load->model("archive_attachment_model");
		$this->load->model("archive_info_model");
		$this->load->model("person_relation_model");
		$this->load->model("archive_attachment_pdf_model");
		$this->load->library('session');
//		$this->department_id=$_SESSION['user_info']['department_id'];
//		$this->uid=$_SESSION['user_info']['id'];
//		$this->group_id=$_SESSION['user_info']['group_id'];
	}


	private $path='/uploads/attachment/pdf/';


   public function index()

   {
       //$this->load->view('admin/common/header');
       $this->load->view('admin/archive/list');
   }



	public function get_archive_limit_json($condition="")
	{
		$page 	= isset($_POST['page']) ? intval($_POST['page']) : 1;
    	$rows 	= isset($_POST['rows']) ? intval($_POST['rows']) : 20;
    	$sort 	= isset($_POST['sort']) ? strval($_POST['sort']) : "a.id";
    	$order 	= isset($_POST['order']) ? strval($_POST['order']) : 'desc';
    	$offset = ($page-1)*$rows;
    	$result 	= $this->archive_model->get_archive_array_limit($offset,$rows,$sort,$order,$condition);
    	$total 		= $this->archive_model->get_archive_rows($condition);
    	$arr 		= array(
			    			"total"=> $total,
			    			"rows" => $result
			    		);

    	$json_str = json_encode($arr);
    	echo $json_str;
	}

	public function get_archive_attachment_limit_json($archive_id=0)
	{
		if($archive_id==0){
			echo NULL;
			die;
		}
		$page 	= isset($_POST['page']) ? intval($_POST['page']) : 1;
    	$rows 	= isset($_POST['rows']) ? intval($_POST['rows']) : 9999;
    	$sort 	= isset($_POST['sort']) ? strval($_POST['sort']) : "a.id";
    	$order 	= isset($_POST['order']) ? strval($_POST['order']) : 'desc';
		$result = $this->archive_attachment_model->get_archive_attachment_limit_json($archive_id,$rows,$page);

    	$json_str = json_encode($result);
    	echo $json_str;
	}

	public function get_archive_info_limit_json($archive_id=0)
	{
		$condition  =  array("archive_id" => $archive_id);
		$result = $this->archive_info_model-> get_archive_info_limit_json($condition);

    	$json_str = json_encode($result);
    	echo $json_str;
	}

	public function add(){

    		if($this->input->is_ajax_request()) {  // 是否ajax提交
				$this->data = $this->input->post();
				unset($this->data["id"]);

				$this->data["receive_time"] 	= strtotime($this->data["receive_time"]);
				$this->data["archive_time"] 	= strtotime($this->data["archive_time"]);
				$this->data["over_time"] 		= strtotime($this->data["over_time"]);
				$this->data["litigant_date"] 	= strtotime($this->data["litigant_date"]);
				$this->data["update_time"] 		=  time();
				$id 	= $this->table_model->add("archive",$this->data);
		        if($id ) {
//		      		$data   =  array("archive_id" => $id);
//					$id 	= $this->table_model->add("archive_attachment",$data);

		       	 	$this->success("添加成功");
		        }else{
		       	 	$this->error("添加失败");
		        }
    		}else{
    			$data['is_readonly']  		= 0;        //1 只读
    			$data["edit_type"]			= "add";
    			$data['action_url']			= site_url("/admin/archive/add");
	   			$data["info"] 				= $this->archive_model->get_archive_fields();
    			$this->load->view('admin/common/header_s');
	       		$this->load->view('admin/archive/edit',$data);
    		}
	}

 	public function edit($id = 0)
    {
    	if($this->input->is_ajax_request()) {  // 是否ajax提交
		    $this->data = $this->input->post();
		    unset($this->data["id"]);
	       	$condition  	=  array("id"	     =>	trim($this->input->post("id")));

	       	$this->data["update_time"] =  time();
	       	$this->data["litigant_date"] =  strtotime($this->data["litigant_date"]);
	       	$this->data["receive_time"] =  strtotime($this->data["receive_time"]);
	       	$this->data["archive_time"] =  strtotime($this->data["archive_time"]);
	       	$this->data["over_time"] =  strtotime($this->data["over_time"]);
	        $result 					= $this->table_model->save("archive",$condition,$this->data) ;
//			p($this->db->last_query());
	        if($result) {
				json_return('ok','修改成功');
	        }else{
				json_return('error','修改失败');
	        }
		}else{

 			$data['action_url']		= site_url("/admin/archive/edit");
 			$data['is_readonly']  		= 0;        //1 只读
 			$condition  	=  array("id"	     =>	$id);
 			$data['info']			= $this->archive_model->get_archive_info($condition);
 			$data['info']["receive_time"]  	=  date("Y-m-d H:i",$data['info']["receive_time"]);
 			$data['info']["archive_time"]  	=  date("Y-m-d H:i",$data['info']["archive_time"]);
 			$data['info']["over_time"]  	=  date("Y-m-d H:i",$data['info']["over_time"]);
 			$data['info']["litigant_date"] 	=  date("Y-m-d H:i",$data['info']["litigant_date"]);
			$this->load->view('admin/common/header_s');
       		$this->load->view('admin/archive/edit',$data);
		}




    }
    public function detail($id = 0)
    {
    	 	$data['action_url']		= site_url("/admin/archive/edit");
 			$data['is_readonly']  		= 1;        //1 只读
 			$condition  	=  array("id"	     =>	$id);
 			$data['info']			= $this->archive_model->get_archive_info($condition);
 			$data['info']["receive_time"]  	=  date("Y-m-d H:i",$data['info']["receive_time"]);
 			$data['info']["archive_time"]  	=  date("Y-m-d H:i",$data['info']["archive_time"]);
 			$data['info']["over_time"]  	=  date("Y-m-d H:i",$data['info']["over_time"]);
 			$data['info']["litigant_date"] 	=  date("Y-m-d H:i",$data['info']["litigant_date"]);
			$this->load->view('admin/common/header_s');
       		$this->load->view('admin/archive/edit',$data);

    }

    public function del()
    {
	    if($this->input->post("id")){
		    $condition      		= array("id" => $this->input->post("id"));
	        if($this->table_model->del("archive",$condition)){
	        	 $this->success("删除成功");
	        }else{
	        	 $this->error("删除失败");
	        }
	    }else{
	    	$this->error("非法访问");
	    }

    }


    public function del_msg()
    {
	    if($this->input->post("id")){
		    $condition      		= array("id" => $this->input->post("id"));
	        if($this->table_model->del("archive_info",$condition)){
	        	 $this->success("删除成功");
	        }else{
	        	 $this->error("删除失败");
	        }
	    }else{
	    	$this->error("非法访问");
	    }

    }

     public function search(){
	       $para  		= $this->input->get();
		 p($para);
		   $condition 	= "";
	       if($para) {
		   	   if($para["word_no"] !="") {
		        	$condition["like"]["a.word_no"]  		= trim($para["word_no"]);
		        }
		        if($para["litigant_name"] !="") {
		        	$condition["like"]["a.litigant_name"]  		= trim($para["litigant_name"]);
		        }
		        if($para["litigant_card"] !="") {
		        	$condition["where"]["a.litigant_card"]  		= trim($para["litigant_card"]);
		        }
			   $this->get_archive_limit_json($condition);
	       }

     }

  	public function edit_attachment($id=1,$name="cover"){

			if($this->input->is_ajax_request()) {  // 是否ajax提交
 				$this->data = $this->input->post();
			    if($this->data["filename"] !=""){
	 				$target_path 	= 'uploads/attachment/pdf/'.getDatePath();
					if (!file_exists($target_path)) {
		  	           mkdir($target_path, 0, true);
		               chmod($target_path,0777);
			        }

			        $FileUtil 	= new FileUtil();
			        $temp_path	= "uploads/temp/";
				    if($FileUtil->moveFile($temp_path.$this->data["filename"],$target_path."/".$this->data["filename"])) {
				    	$condition = array("archive_id"  =>$this->data["id"]);
				    	$data		= array($this->data["name"]=>"/".$target_path."/".$this->data["filename"]);
				    	$result 	= $this->table_model->save("archive_attachment",$condition,$data) ;
                         $this->success("修改成功");

				    }else{
						$this->error("修改失败");
				    }
			    }else{
						$this->error("修改失败");
			    }
			}else{
				$data['action_url']	= site_url("/admin/archive/edit_attachment");
				$condition			= array("archive_id" => $id);
			    $info				= $this->table_model->get_array_one("archive_attachment",$condition);
			    $file 				= pathinfo($info[$name]);
				$data["info"]		= array("id"=>$id,"name"=>$name,"file_url"=>$file["basename"]);
				$this->load->view('admin/common/header_s');
	       		$this->load->view('admin/archive/attachment_edit',$data);
			}
  	}


   public function upload(){
        $file  	 = $this->input->post("file");

        $pdfname = $_FILES[$file]['name'];
       	$pdfsize = $_FILES[$file]['size'];
        if ($pdfname != "") {
            if ($pdfsize > 10240000) {
                echo 'PDF大小不能超过10M';
                exit;
            }
            $type = strstr($pdfname, '.');
            if ($type != ".pdf") {
                echo '文件格式不对！';
                exit;
            }

            $rand 		= rand(100000, 999+999);
            $pic 		= uniqid(date("YmdHis").$rand) . $type;
            $pic_path 	= "uploads/temp/".$pic;
            //上传路径
            move_uploaded_file($_FILES[$file]['tmp_name'], $pic_path);
            $size = round($pdfsize/1024,2);
	        $arr = array(
	            "status"		=> 1,
				'filename'		=> $pic
	        );

        }else{
        	$arr = array(
	            "status"		=> 0,
				'message'		=> "文件上传出错"
	        );
        }
             echo json_encode($arr);

    }

     public function uploadsave(){

            if (isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
				$upload_file 	= $_FILES['Filedata'];
				$file_info   	= pathinfo($upload_file['name']);
				$file_type   	= $file_info['extension'];
				$imageName   	= md5(uniqid($_FILES["Filedata"]['name'])) . '.' . $file_info['extension'];
				$name        	= $_FILES['Filedata']['tmp_name'];
				$image_path		= "uploads/temp/".$imageName;
				if (move_uploaded_file($name, $image_path)) {
					echo $imageName;
				}
            }
 	}

	public function archive_info(){
		$id  = $this->input->get("id");

		$condition	= array("id" => $id);
		$data["info"]		= $this->table_model->get_array_one("archive",$condition);
		if(empty($data["info"]["content"])){
			$data["info"]["content"] = array();
		}else{
			$data["info"]["content"] = unserialize($data["info"]["content"]);
		}
		$data["id"]  		=  $id;
		//$this->load->view('admin/common/header');
	    $this->load->view('admin/archive/archive_info',$data);

	}
	public function add_info($id=0){

		if($this->input->is_ajax_request()) {  // 是否ajax提交

			$this->data 	= $this->input->post();
			$id 			= $this->data["id"];
			$person_select	= $this->data["person_select"];
			if(isset($this->data["person_bealive"])){
				$person_bealive	= $this->data["person_bealive"];
				unset($this->data["person_bealive"]);
			}else{
				$person_bealive	= 1;
			}
			if(isset($this->data["person_relation_id"])){
				$person_relation_id	= $this->data["person_relation_id"];
				unset($this->data["person_relation_id"]);
			}else{
				$person_relation_id	= 0;
			}

			$condition		= array("id" => $id);
			$archive		= $this->table_model->get_array_one("archive",$condition);
	        unset($this->data["person_select"]);
	        unset($this->data["muti_select"]);
	        unset($this->data[0]);
	        unset($this->data["id"]);
	        $content		= $this->data;
        	$result 	=  array();

             foreach($content  as $key=>$row) {
				$temp =	explode("|",$key);
				$group = $temp[0];
				$result[$group][$temp[1]] =  $row;
				unset($content[$group][$temp[1]]);
        	}

			$data["archive_id"]  		= $id;
			$data["litigant_name"]  	= $archive["litigant_name"];
			$data["litigant_card"]  	= $archive["litigant_card"];
			$data["litigant_sex"]  		= $archive["litigant_sex"];
			$data["litigant_date"]  	= $archive["litigant_date"];
			$data["litigant_status"]  	= 1;

			if($person_select ==1){
				$data["related_name"]  	= $archive["litigant_name"];
				$data["related_card"]  	= $archive["litigant_card"];
				$data["related_sex"]  	= $archive["litigant_sex"];
				$data["related_date"]  	= $archive["litigant_date"];
				$data["related_status"] = 1;
			}else{
				$data["related_name"]  	= $result["person"]["姓名"];
				$data["related_sex"]  	= $result["person"]["性别"];
				$data["related_card"]  	= $result["person"]["身份证号"];
				$data["related_date"]  	= $result["person"]["出生日期"];
				$data["related_status"] = 1;
			}

			if($person_bealive ==1){
				$data["related_status"]		= 1;
			}else{
				$data["related_status"]		= 2;
			}

			$data["person_relation_id"]  	= $person_relation_id;
			$data["related_type"]			= $person_select;
			$data["content"]				= serialize($result);
	        $result = $this->table_model->add("archive_info",$data) ;
	        if($result) {
	       	 	$this->success("添加成功");
	        }else{
	       	 	$this->error("添加失败");
	        }
		}else{
			//$id=   $this->input->get("id");

			$condition	= array("id" => $id);
			$archive	=	$this->table_model->get_array_one("archive",$condition);
			$notary_matter_id = $archive["notary_matter_id"];

			$condition	= array("id" => $notary_matter_id);
			$data["notary_matter"]	= $this->table_model->get_array_one("notary_matter",$condition);

			$condition	= array("pid" => $notary_matter_id);
			$data["notary_matter_para"]	= $this->table_model->get_array("notary_matter",$condition);

			$data["person"]				= $this->notary_matter_model->get_person_fields();

			$data['action_url']			= site_url("admin/archive/add_info");
			$data['id']					= $id;
			$this->load->view('admin/common/header_s');
	       	$this->load->view('admin/archive/add_info',$data);
		}
	}



  public function edit_info($id=0){

		if($this->input->is_ajax_request()) {  // 是否ajax提交

			$this->data 	= $this->input->post();
			$id 			= $this->data["id"];
			$person_select	= $this->data["person_select"];
			if(isset($this->data["person_bealive"])){
				$person_bealive	= $this->data["person_bealive"];
				unset($this->data["person_bealive"]);
			}else{
				$person_bealive	= 1;
			}
			if(isset($this->data["person_relation_id"])){
				$person_relation_id	= $this->data["person_relation_id"];
				unset($this->data["person_relation_id"]);
			}else{
				$person_relation_id	= 0;
			}

			$condition		= array("id" => $id);
			$archive		= $this->table_model->get_array_one("archive",$condition);
	        unset($this->data["person_select"]);
	        unset($this->data["muti_select"]);
	        unset($this->data[0]);
	        unset($this->data["id"]);
	        $content		= $this->data;
        	$result 	=  array();

             foreach($content  as $key=>$row) {
				$temp =	explode("|",$key);
				$group = $temp[0];
				$result[$group][$temp[1]] =  $row;
				unset($content[$group][$temp[1]]);
        	}

			$data["archive_id"]  		= $id;
			$data["litigant_name"]  	= $archive["litigant_name"];
			$data["litigant_card"]  	= $archive["litigant_card"];
			$data["litigant_sex"]  		= $archive["litigant_sex"];
			$data["litigant_date"]  	= $archive["litigant_date"];
			$data["litigant_status"]  	= 1;

			if($person_select ==1){
				$data["related_name"]  	= $archive["litigant_name"];
				$data["related_card"]  	= $archive["litigant_card"];
				$data["related_sex"]  	= $archive["litigant_sex"];
				$data["related_date"]  	= $archive["litigant_date"];
				$data["related_status"] = 1;
			}else{
				$data["related_name"]  	= $result["person"]["姓名"];
				$data["related_sex"]  	= $result["person"]["性别"];
				$data["related_card"]  	= $result["person"]["身份证号"];
				$data["related_date"]  	= $result["person"]["出生日期"];
				$data["related_status"] = 1;
			}

			if($person_bealive ==1){
				$data["related_status"]		= 1;
			}else{
				$data["related_status"]		= 2;
			}

			$data["person_relation_id"]  	= $person_relation_id;
			$data["related_type"]			= $person_select;
			$data["content"]				= serialize($result);
			$data["create_time"]			= time();
	        $result = $this->table_model->add("archive_info",$data) ;
	        if($result) {
	       	 	$this->success("添加成功");
	        }else{
	       	 	$this->error("添加失败");
	        }
		}else{

			$condition		= array("id" => $id);
			$data["info"]	=	$this->table_model->get_array_one("archive_info",$condition);

			$condition	= array("id" => $data["info"]["archive_id"]);

			$archive	=	$this->table_model->get_array_one("archive",$condition);
			$notary_matter_id = $archive["notary_matter_id"];

			$condition	= array("id" => $notary_matter_id);
			$data["notary_matter"]	= $this->table_model->get_array_one("notary_matter",$condition);

			$condition	= array("pid" => $notary_matter_id);
			$data["notary_matter_para"]	= $this->table_model->get_array("notary_matter",$condition);
			$data["person"]				= $this->notary_matter_model->get_person_fields();

            if($data["info"]["content"] != ""){
            	$data["info"]["content"] = unserialize($data["info"]["content"]);
            }else{
            	$data["info"]["content"] =  array();
            }
            $info_value =  array();
            $group_info = array();
            foreach($data["info"]["content"]  as $key=> $row) {
            	if($key != "person") {
         				foreach($row  as $rowkey=>$val){
         					$info_value[$key."|".$rowkey]  = $val;
         				}
            	}

            }

            $data["info_value"] = $info_value;

			$data['action_url']			= site_url("admin/archive/add_info");
			$data['id']					= $id;
			$this->load->view('admin/common/header_s');
	       	$this->load->view('admin/archive/edit_info',$data);
		}
	}
	public function get_storage_time_json(){
			$temp  	= $this->archive_model->get_storage_time_array();
			$result = array();
			foreach($temp  as $key=>$row) {
				$result[] =  array("id"=>$key,"text"=>$row);
			}
			$json_str 	= json_encode($result);
    		echo $json_str;
	}

	public function get_person_relation_json(){
			$result 	= $this->person_relation_model->get_person_relation_json();
			echo $result;
	}

  	public function show_file($id=0,$name){

  			$condition		= array("archive_id" => $id);
			$info	=	$this->table_model->get_array_one("archive_attachment",$condition);

			$data["file_url"]  = $info[$name];
			$data	=  array();
			$this->load->view('admin/common/header_s');
	       	$this->load->view('admin/archive/pdf_show',$data);
  	}


    /*
     * 年度业务量统计
     * */
    public function business_statistics(){
		if($this->user_info['group_id']==1){
//        $this->output->cache(10);//页面缓存,分钟
			$statistics=$this->archive_model->business_statistics();
		}elseif($this->user_info['group_id']==2){
			$statistics=$this->archive_model->business_statistics('department_id='.$this->user_info['department_id']);
		}else{
			echo '你没有权限查看';
			die;
		}
		if($statistics==NULL){
			echo '没有数据';
			die;
		}
		$data['statistics']=json_encode($statistics);
		$this->load->view('admin/common/header');
		$this->load->view('admin/archive/business_statistics',$data);
    }

    /*
     * 公证类别
     * */
    public function notarial_category(){
//        $this->output->cache(10);//页面缓存,分钟
		if($this->user_info['group_id']==1){
			$category=$this->archive_model->notarial_category();
		}elseif($this->user_info['group_id']==2){
			$w['a.department_id']=$this->user_info['department_id'];
			$category=$this->archive_model->notarial_category($w);
		}else{
			echo '你没有权限查看';
			die;
		}
		if($category==NULL){
			echo '没有数据';
			die;
		}
        $data['category']=json_encode($category);
        $this->load->view('admin/common/header');
        $this->load->view('admin/archive/notarial_category',$data);
    }

    /*
     * 公证事由分析
     * */
    public function notary_matter(){
//        $this->output->cache(10);//页面缓存,分钟


		if($this->user_info['group_id']==1){
			$res=$this->archive_model->notary_matter();
		}elseif($this->user_info['group_id']==2){
			$w['department_id']=$this->user_info['department_id'];
			$res=$this->archive_model->notary_matter($w);
		}else{
			echo '你没有权限查看';
			die;
		}
		if($res==NULL){
			echo '没有数据';
			die;
		}
        $data['notary_matter']=json_encode($res);
        $this->load->view('admin/common/header');
        $this->load->view('admin/archive/notary_matter',$data);
    }

    /*
     * 公证事由分析数据
     * */
    public function notary_matter_json(){
        $res=$this->archive_model->notary_matter();
        echo json_encode($res);
    }

    /*
     * 实时数据监控
     * */
    public function real_time_data(){
        $res=$this->archive_model->real_time_data();
        $data['data']=json_encode($res);
        $this->load->view('admin/common/header');
        $this->load->view('admin/archive/real_time_data',$data);
    }

    /*
     * 档案查询
     * */
    public function archive_index(){
        $this->load->view('admin/common/header');
        $this->load->view('admin/archive/index');
    }

    /*
     * 档案查询json数据
     * */
    public function archive_index_json(){
//        receive_year,category_id,notary_matter_id,word_no,litigant_name,litigant_card,storage_time,box_number,volume_number,department_id
        $where=array();
        $like=array();
        $page=isset($_POST['page'])?$_POST['page']:1;
        $rows=isset($_POST['rows'])?$_POST['rows']:50;
        $department_id=isset($_POST['department_id'])?$_POST['department_id']:0;
//        $receive_year=isset($_POST['receive_year'])?$_POST['receive_year']:'';//年份
//        $category_id=isset($_POST['category_id'])?$_POST['category_id']:0;//类别
		$notary_matter=isset($_POST['notary_matter'])?$_POST['notary_matter']:'';
        $greffier=isset($_POST['greffier'])?$_POST['greffier']:'';
        $undertaker=isset($_POST['undertaker'])?$_POST['undertaker']:'';
        $word_no=isset($_POST['word_no'])?$_POST['word_no']:'';
        $litigant_name=isset($_POST['litigant_name'])?$_POST['litigant_name']:'';
        $litigant_card=isset($_POST['litigant_card'])?$_POST['litigant_card']:'';

//		p($notary_matter);
		$receive_time_chk=isset($_POST['receive_time_chk'])?$_POST['receive_time_chk']:false;
		$receive_time_from=isset($_POST['receive_time_from'])?$_POST['receive_time_from']:'';
		$receive_time_to=isset($_POST['receive_time_to'])?$_POST['receive_time_to']:'';

		$over_time_chk=isset($_POST['over_time_chk'])?$_POST['over_time_chk']:false;
		$over_time_from=isset($_POST['over_time_from'])?$_POST['over_time_from']:'';
		$over_time_to=isset($_POST['over_time_to'])?$_POST['over_time_to']:'';
//		if($department_id==-1){
//			echo array('rows'=>array(),'total'=>0);
//			die;
//		}
//        $storage_time_id=isset($_POST['storage_time_id'])?$_POST['storage_time_id']:'-1';//保存期限
//        $box_number=isset($_POST['box_number'])?$_POST['box_number']:'';//盒号
//        $volume_number=isset($_POST['volume_number'])?$_POST['volume_number']:'';//卷号
        if($department_id!=0){
            $where['a.department_id']=$department_id;
        }
//        if($receive_year!=''){
//            $where['a.receive_year']=$receive_year;
//        }
//        if($category_id!=0){
//            $where['a.category_id']=$category_id;
//        }
        if($notary_matter!=''){
            $like['a.notary_matter_name']=$notary_matter;
        }
        if($greffier!=''){
            $like['a.greffier']=$greffier;
        }
        if($undertaker!=''){
            $like['a.undertaker']=$undertaker;
        }
        if($word_no!=''){
            $like['a.word_no']=$word_no;
        }
        if($litigant_name!=''){
            $like['a.litigant_name']=$litigant_name;
        }
        if($litigant_card!=''){
            $where['a.litigant_card']=$litigant_card;
        }
		//日期判断
//		print_r($receive_time_chk);
		if($receive_time_chk=='true'){
			if($receive_time_from!=''){
				$where['a.receive_time >=']=strtotime($receive_time_from);
			}
			if($receive_time_to!=''){
				$where['a.receive_time <=']=strtotime($receive_time_to);
			}
		}
		if($over_time_chk=='true'){
			if($over_time_from!=''){
				$where['a.over_time >=']=strtotime($over_time_from);
			}
			if($over_time_to!=''){
				$where['a.over_time <=']=strtotime($over_time_to);
			}
		}
//        if($storage_time_id!='-1'){
//            $where['a.storage_time_id']=$storage_time_id;
//        }
//        if($box_number!=''){
//            $where['a.box_number']=$box_number;
//        }
//        if($volume_number!=''){
//            $where['a.volume_number']=$volume_number;
//        }
//		print_r($page);
        $res=$this->archive_model->get_archive_list($where,$rows,$page,'id desc',$like);
        echo json_encode($res);
    }



    /*
     * 获取档案是否可以查阅的状态
     * */
    public function get_archive_status(){
        $id=$_GET['id'];
        $where['id']=$id;
        $res=$this->archive_model->get_archive_detail($where,'id,new_number,department_id,greffier');
        if($res==NULL){
            echo '档案不存在';
        }else{
			//查看是否有权限
			//1.主任查看本公证处所有档案
			//2.普通员工只能查看和自己相关的档案
			//3.默认可以看目录和正文
			//4.超级管理员查看所有
            if(
				($res['department_id']==$this->department_id&&$this->user_info['group_id']==2)//主任且本部门
				||
				$this->user_info['group_id']==1//管理员
				||
				($this->user_info['account']==trim($res['greffier']))//普通人员且是公证员
			){
                //本公证处的档案,直接显示
				//获取pdf
				unset($where);
				$where['archive_id']=$id;
				$r=$this->archive_attachment_pdf_model->get_pdf($where,'new_number,file_name');
				if($r==NULL){
					echo 'pdf文件不存在';
				}else{
					for($i=0;$i<count($r);$i++){
						$tree[]=array(
                            'text'=>$r[$i]['file_name'],
                            'attributes'=>array('url'=>$this->path.$this->department_id.'/'.$r[$i]['new_number'].'.pdf')
                        );
					}
					$data['archive']=$res;
					$data['re_applicant']=false;
					$data['tree']=json_encode($tree);
					$this->load->view('admin/common/header');
					$this->load->view('admin/archive/pdf_view',$data);
				}
            }else{
                //非本公证处的档案,查询是否有申请查阅,查询申请是否通过
                unset($where);
                $where['archive_id']=$id;
                $where['uid']=$this->uid;
                $applicant_res=$this->archive_applicant_model->get_archive_applicant_detail($where);//查询审批状态
				if($applicant_res==NULL||$applicant_res['review']==0||$applicant_res['review']==2){
					//显示默认2项
					unset($where);
					$where['archive_id']=$id;
					$where_in=array('卷内目录','公证书正文');
					$r=$this->archive_attachment_pdf_model->get_pdf($where,'new_number,file_name',$where_in);
					if($r==NULL){
						echo 'pdf文件不存在';
					}else{
						for($i=0;$i<count($r);$i++){
							$tree[]=array(
								'text'=>$r[$i]['file_name'],
								'attributes'=>array('url'=>$this->path.$this->department_id.'/'.$r[$i]['new_number'].'.pdf')
							);
						}
						$data['archive']=$res;
						$data['re_applicant']=true;
						$data['tree']=json_encode($tree);
						$this->load->view('admin/common/header');
						$this->load->view('admin/archive/pdf_view',$data);
					}
				}else{
					//显示默认+审核通过的
					unset($where);
					$where['archive_id']=$id;
					$where_in=array('卷内目录','公证书正文');
					$r=$this->archive_attachment_pdf_model->get_pdf($where,'new_number,file_name',$where_in);
					if($r==NULL){
						echo 'pdf文件不存在';
					}else{
						for($i=0;$i<count($r);$i++){
							$tree[]=array(
								'text'=>$r[$i]['file_name'],
								'attributes'=>array('url'=>$this->path.$this->department_id.'/'.$r[$i]['new_number'].'.pdf')
							);
						}
						$select_files=unserialize($applicant_res['files']);
						$files=$this->_get_audition_applicant_list($id);
						foreach($select_files as $key=>$val){
							//判断是否是选中文件
							if($files[$key][0]=='卷内目录'||$files[$key][0]=='公证书正文'){
								continue;
							}
							$tree[]=array(
								'text'=>$files[$key][0],
								'attributes'=>array('url'=>$files[$key][1]),
							);
						}
						$data['archive']=$res;
						$data['re_applicant']=true;
						$data['tree']=json_encode($tree);
						$this->load->view('admin/common/header');
						$this->load->view('admin/archive/pdf_view',$data);
					}
				}
//                if($applicant_res==NULL){
//                    $this->show_applicant($id);
//                }elseif($applicant_res['review']==0){
//                    //审核中
//                    $select_files=unserialize($applicant_res['files']);
//                    $this->show_applicant($id,0,$select_files,'申请审核中,您可以修改查阅申请',$applicant_res['reason']);
//                }elseif($applicant_res['review']==1){
//                    //同意
//                    //显示通过审核的档案
////                    $pdf=$this->archive_attachment_model->get_attachment_detail($id);
//                    $select_files=unserialize($applicant_res['files']);
//					$files=$this->_get_audition_applicant_list($id);
//                    $tree=array();
//                    foreach($select_files as $key=>$val){
//						//判断是否是选中文件
//						$tree[]=array(
//							'text'=>$files[$key][0],
//							'attributes'=>array('url'=>$files[$key][1]),
//						);
//                    }
//                    $data['archive']=$res;
//                    $data['re_applicant']=true;
//                    $data['tree']=json_encode($tree);
//					$this->load->view('admin/common/header');
//                    $this->load->view('admin/archive/pdf_view',$data);
//                }elseif($applicant_res['review']==2){
//                    //驳回
//                    $select_files=unserialize($applicant_res['files']);
//                    $this->show_applicant($id,0,$select_files,'审核不通过,您可以重新发起查阅申请',$applicant_res['reason']);
//                }else{
//                    echo '未知错误,请联系系统管理员';
//                }
            }
        }
    }

    /*
     * 审核成功后再次提交申请
     * */
    public function re_applicant(){
        $archive_id=$_GET['archive_id'];
        $where['archive_id']=$archive_id;
        $where['uid']=$this->uid;
        $applicant_res=$this->archive_applicant_model->get_archive_applicant_detail($where);
        $select_files=unserialize($applicant_res['files']);
        $this->show_applicant($archive_id,0,$select_files,'再次提交申请将会使之前的通过失效',$applicant_res['reason']);
    }

    /*
     * 申请查阅界面
     * $my_files 我申请的查阅 选中的.
     * */
    public function show_applicant($archive_id,$status=-1,$my_files=array(),$msg='',$reason=''){
        $files=$this->_get_applicant_list($archive_id);
        $tree=array();
		foreach($files as $key=>$val){
			if($val=='卷内目录'||$val=='公证书正文'){
				continue;
			}
			$tree[]=array(
				'text'=>$val,
				'attributes'=>array('value'=>$key),
				'checked'=>isset($my_files[$key])?true:false
			);
		}
//		p($tree);
        $data['tree']=json_encode($tree);
        $data['msg']=$msg;
        $data['archive_id']=$archive_id;
        $data['reason']=$reason;
        $data['status']=$status;

        $this->load->view('admin/common/header');
        $this->load->view('admin/archive/applicant_view',$data);
    }

    /*
     * 提交查阅申请
     * */
    public function sub_applicant(){
        //uid,archive_id,files,reason
        //sub_applicant($where,$data)
        $files=$_POST['files'];
        $reason=$_POST['reason'];
        $archive_id=$_POST['archive_id'];
        if(count($files)==0){
            json_return('error','您尚未选择需要查阅的档案');
        }
        for($i=0;$i<count($files);$i++){
            $new_files[$files[$i]]='';
        }
        $where['uid']=$this->uid;
        $where['archive_id']=$archive_id;
        $data['reason']=$reason;
        $data['review']=0;
        $data['uid']=$this->uid;
        $data['archive_id']=$archive_id;
        $data['create_time']=time();
        $data['files']=serialize($new_files);
        $res=$this->archive_applicant_model->sub_applicant($where,$data);
        if($res){
			//获取主任uid
			$d['apply_id']=$res;
			$r=$this->archive_applicant_model->get_manage_uid($archive_id);
			$d['uids']=$r;
			$d['nickname']=$this->user_info['nickname'];
			$d['department_name']=$this->user_info['department_name'];
            json_return('ok','查阅申请提交成功,等待审核',$d);
        }else{
            json_return('error','查阅申请提交失败,请稍后再尝试');
        }
    }

    /*
     * 获取申请列表
     * */
    private function _get_applicant_list($archive_id){
		$where['id']=$archive_id;
		$archive_res=$this->archive_model->get_archive_detail($where,'id,new_number,department_id');
		if($archive_res==NULL){
			echo '档案信息不存在';
			die;
		}else{
			//档案存在,查询目录是否存在
			unset($where);
			$where['archive_id']=$archive_id;
			$pdf_res=$this->archive_attachment_pdf_model->get_pdf($where,'id,file_name');
			if($pdf_res==NULL){
				echo '目录信息不存在';
				die;
			}
			$array=array();
			for($i=0;$i<count($pdf_res);$i++){
				$array[$pdf_res[$i]['id']]=$pdf_res[$i]['file_name'];
//				$tree[]=array(
//					'text'=>$archive_res[$i]['file_name'],
//					'attributes'=>array('url'=>$this->path.$archive_res[$i]['department_id'].'/'.$archive_res[$i]['new_number'].'.pdf')
//				);
			}
			return $array;
		}
//        $array=array(
////            'archive_id'=>'档案ID',
//            'cover'							=>'封面',
//            'directory'						=>'目录',
//            'notary_content'				=>'公证书正文',
//            'notary_draft'					=>'公证书签发稿',
//            'notary_appform'				=>'公证书申请表',
//            'notary_notice'					=>'公证受理通知书',
//        	'notification'					=>'告知书',
//            'litigant_card'					=>'当事人的身份证明',
//            'litigant_prove'				=>'当事人提供的证明材料',
//            'conversation_record'			=>'谈话笔录',
//            'notary_sent_back'				=>'公证书送达回执',
//            'notary_fee_receipt'			=>'公证收费收据',
//            'reference_table'				=>'备考表',
//            'norary_translation'			=>'公证书译文',
//            'review_material'				=>'审查,调查所取得证明材料',
//            'audit_table'					=>'发证审核表',
//            'litigant_apply_prove_original'	=>'当事人申请证明文书材料原件',
//            'attachment_bag'				=>'附件袋',
//            'other_material'				=>'其它材料'
//        );
//        return $array;
    }


	/*
     * 获取申请列表
     * */
	private function _get_audition_applicant_list($archive_id){
		$where['id']=$archive_id;
		$archive_res=$this->archive_model->get_archive_detail($where,'id,new_number,department_id');
		if($archive_res==NULL){
			echo '档案信息不存在';
			die;
		}else{
			//档案存在,查询目录是否存在
			unset($where);
			$where['archive_id']=$archive_id;
//			$like['new_number']=$archive_res['new_number'];
			$pdf_res=$this->archive_attachment_pdf_model->get_pdf($where,'id,file_name,new_number');
			if($pdf_res==NULL){
				echo '目录信息不存在';
				die;
			}
			$array=array();
			for($i=0;$i<count($pdf_res);$i++){
				$array[$pdf_res[$i]['id']]=array($pdf_res[$i]['file_name'],$this->path.$archive_res['department_id'].'/'.$pdf_res[$i]['new_number'].'.pdf');
//				$tree[]=array(
//					'text'=>$archive_res[$i]['file_name'],
//					'attributes'=>array('url'=>$this->path.$archive_res[$i]['department_id'].'/'.$archive_res[$i]['new_number'].'.pdf')
//				);
			}
			return $array;
		}
	}

    /*
     * 申请管理
     * */
    public function apply_manage(){
//        if($this->group_id!=2){
//            echo '您没有权限查看';
//            die;
//        }
        $this->load->view('admin/common/header');
        $this->load->view('admin/archive/apply_manage');
    }

    /*
     * 申请管理数据json
     * */
    public function apply_manage_json(){
        if($this->group_id!=2){
            die;
        }
        $where=array();
        $like=array();
        $page=isset($_POST['page'])?$_POST['page']:1;
        $rows=isset($_POST['rows'])?$_POST['rows']:20;
        $word_no=isset($_POST['word_no'])?$_POST['word_no']:'';
        $review=isset($_POST['review'])?$_POST['review']:0;
        $litigant_name=isset($_POST['litigant_name'])?$_POST['litigant_name']:'';
        $litigant_card=isset($_POST['litigant_card'])?$_POST['litigant_card']:'';
        $where['a.department_id']=$this->department_id;
        if($word_no!=''){
            $like['a.word_no']=$word_no;
        }
        if($review!=-1){
            $where['apply.review']=$review;
        }
        if($litigant_name!=''){
            $like['a.litigant_name']=$litigant_name;
        }
        if($litigant_card!=''){
            $like['a.litigant_card']=$litigant_card;
        }
//        $res=$this->archive_model->get_archive_list($where,$rows,$page,'id desc',$like);
//		p($where);
        $res=$this->archive_model->get_apply_manage($where,$rows,$page,'id desc',$like);
        echo json_encode($res);
    }

    /*
     * 申请审核
     * */
    public function apply_audition(){
        if($this->group_id!=2){
            echo '您没有权限查看';
            die;
        }
        $id=$_GET['id'];
		$reload=isset($_GET['reload'])?$_GET['reload']:1;
        $condition['id']=$id;
        $apply_res=$this->archive_applicant_model->get_archive_applicant_detail($condition);
        if($apply_res==NULL){
            echo '数据不存在';
            die;
        }
        $this->_check_auth($apply_res['archive_id']);
//        $pdf_res=$this->archive_attachment_model->get_attachment_detail($apply_res['archive_id']);
        //tree数据组装
        $apply_files=unserialize($apply_res['files']);
        $files=$this->_get_audition_applicant_list($apply_res['archive_id']);
        $tree=array();
        foreach($files as $key=>$val){
			if($val[0]=='卷内目录'||$val[0]=='公证书正文'){
				continue;
			}
            $tree[]=array(
                'text'=>$val[0],
                'attributes'=>array('value'=>$key,'url'=>$val[1]),
                'checked'=>isset($apply_files[$key])?true:false
            );
        }
        $data['id']=$id;
        $data['apply_uid']=$apply_res['uid'];
        $data['archive_id']=$apply_res['archive_id'];
        $data['tree']=json_encode($tree);
        $data['reason']=$apply_res['reason'];
        $data['reload']=$reload;
        $this->load->view('admin/common/header');
        $this->load->view('admin/archive/apply_audition',$data);
    }

    /*
     * 申请通过
     * */
    public function apply_pass(){
        $id=$_POST['id'];
        $archive_id=$_POST['archive_id'];
        $files=$_POST['files'];
        $this->_check_auth($archive_id);
        if(count($files)==0){
            json_return('error','您尚未选择需要查阅的档案');
        }
        for($i=0;$i<count($files);$i++){
            $new_files[$files[$i]]='';
        }
        $condition['id']=$id;
        $condition['review']=0;
        $data['review']=1;
        $data['files']=serialize($new_files);
        $res=$this->archive_applicant_model->update_applicat($condition,$data);
        if($res===FALSE||$this->db->affected_rows()==0){
            unset($condition);
            $condition['id']=$id;
            $apply_res=$this->archive_applicant_model->get_archive_applicant_detail($condition);
            if($apply_res==NULL){
                json_return('error','数据不存在');
            }elseif($apply_res['review']!=0){
                $str=$apply_res['review']==1?'该查阅申请已被通过,无法操作':'该查阅申请已被驳回,无法操作';
                json_return('error',$str);
            }
        }else{
            json_return('ok','已通过');
        }
    }

    /*
     * 申请驳回
     * */
    public function apply_no_pass(){
        $id=$_POST['id'];
        $archive_id=$_POST['archive_id'];
        $this->_check_auth($archive_id);
        $condition['id']=$id;
        $condition['review']=0;
        $data['review']=2;
        $res=$this->archive_applicant_model->update_applicat($condition,$data);
        if($res===FALSE||$this->db->affected_rows()==0){
            unset($condition);
            $condition['id']=$id;
            $apply_res=$this->archive_applicant_model->get_archive_applicant_detail($condition);
            if($apply_res==NULL){
                json_return('error','数据不存在');
            }elseif($apply_res['review']!=0){
                $str=$apply_res['review']==1?'该查阅申请已被通过,无法操作':'该查阅申请已被驳回,无法操作';
                json_return('error',$str);
            }
        }else{
            json_return('ok','已驳回');
        }
    }

    /*
     * 判断是否有审核某个档案的权限
     * */
    private function _check_auth($archive_id){
        $condition['id']=$archive_id;
        $res=$this->archive_model->get_archive_detail($condition);
        if($res==NULL){
            json_return('error','档案不存在');
        }elseif($res['department_id']!=$this->department_id){
            json_return('error','您没有权限审核');
        }elseif($this->group_id!=2){
            json_return('error','您没有权限审核');
        }
    }

	/*
	 * 获取未读的审批信息
	 * */
	public function get_audition_msg(){
		if($this->group_id!=2){
			json_return('error','');
		}
		$where['a.department_id']=$this->department_id;
		$rows=10;
		$page=1;
		$like=array();
		$res=$this->archive_model->get_apply_manage($where,$rows,$page,'id desc',$like);
		json_return('ok','',$res);
	}

	/*
	 * 检测是否有文件丢失
	 * */
	public function check_merge(){
		$list=$_POST['list'];
		for($i=0;$i<count($list);$i++){
			if(!is_file(substr($list[$i],1))){
				json_return('error','检测到有部分文档丢失,是否跳过丢失文档继续打印?');
			}
		}
		json_return('ok','');
	}

	/*
	 * 合并pdf显示所有
	 * */
	public function merge_all(){
//		$pdf = new \Jurosh\PDFMerge\PDFMerger;
//		$path = "uploads/merge";
//		$merge_name=$path.'/'.time().rand(100000,999999).'_merged.pdf';
//		$list=$_POST['list'];
//		for($i=0;$i<count($list);$i++){
//			if(!is_file(substr($list[$i],1))){
//				continue;
//			}
////			$pdf->addPDF(substr($list[$i],1), 'all', 'horizontal');
//			$pdf->addPDF(substr($list[$i],1), 'all');
//		}
//		$pdf->merge('file',$merge_name);
//		json_return('ok','',$merge_name);


		$list=$_POST['list'];
		$pdf = new FPDI();
		$path = "uploads/merge";
		$merge_name=$path.'/'.time().rand(100000,999999).'_merged.pdf';
		foreach ($list AS $file) {
			// get the page count
			$pageCount = $pdf->setSourceFile(substr($file,1));
			// iterate through all pages
			for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
				// import a page
				$templateId = $pdf->importPage($pageNo);
				// get the size of the imported page
				$size = $pdf->getTemplateSize($templateId);

				// create a page (landscape or portrait depending on the imported page size)
				if ($size['w'] > $size['h']) {
					$pdf->AddPage('L', array($size['w'], $size['h']));
				} else {
					$pdf->AddPage('P', array($size['w'], $size['h']));
				}

				// use the imported page
				$pdf->useTemplate($templateId);

				$pdf->SetFont('Helvetica');
				$pdf->SetXY(5, 5);
//				$pdf->Write(8, 'A simple concatenation demo with FPDI');
			}
		}

// Output the new PDF
		$pdf->output('F',$merge_name);
		if(is_file($merge_name)){
			json_return('ok','',$merge_name);
		}else{
			json_return('error','合并失败');
		}
	}

	/*
	 * 案卷上传
	 * */
	public function uploads(){
//		p($_FILES);
		$prefix=$_POST['pre'];
		$config['upload_path']      = './uploads/excel';
		$config['allowed_types']    = 'xls|xlsx|csv';
		$config['file_name']    = $prefix.'_'.date('YmdHis').rand(100000,999999);
		$config['max_size']     = 1024*10;//尺寸kb
		$this->load->library('upload', $config);

		if ( ! $this->upload->do_upload('file'))
		{
			$error = $this->upload->display_errors();

			json_return('error',$error);
		}
		else
		{
			$d=$this->upload->data();
			$data = array('filepath' => $config['upload_path'].'/'.$d['file_name']);
			//只返回文件大小
//			p($d);
			json_return('ok','',$data);
//			$this->load->view('upload_success', $data);
		}
	}

	/*
	 * 校验公证事项
	 * */
	public function check_notary_matter($str=1){
		$where['name']=trim($str);
		$res=$this->notary_matter_model->get_notary_matter_one($where);
		if($res==NULL){
			//写入
			$data['name']=$str;
			$r=$this->notary_matter_model->add_notary_matter($data);
			if($r==FALSE||$this->db->affected_rows()==0){
				return FALSE;
			}else{
				return $this->db->insert_id();
			}
		}else{
			return $res['id'];
		}
	}

	/*
	 * 案卷写入
	 * */
	public function anjuan_insert(){
		$file=$_POST['file'];
		$start=$_POST['start'];
		$department_id=$_POST['department_id'];
		$length=$_POST['length'];//长度
		$this->load->library('Classes/PHPExcel.php');

		$inputFileType = PHPExcel_IOFactory::identify($file);
		$objReader = PHPExcel_IOFactory::createReader($inputFileType);
		$chunkSize = 50;    // 定义每块读去的行数,每次读取50条
		// 就可在一个循环中，多次读去块，而不用一次性将整个Excel表读入到内存中
		$chunkFilter = new chunkReadFilter($start+1, $chunkSize);
		$objReader->setReadFilter($chunkFilter); // 设置实例化的过滤器对象
		$objPHPExcel = $objReader->load($file);
		$currentSheet = $objPHPExcel->getSheet(0);
//		$allRow = $currentSheet->getHighestRow();
		// 开始读取每行数据，并插入到数据库
//		$d=$objPHPExcel->getActiveSheet()->toArray();

		$this->db->trans_begin();//开启事务
		//写入一个array,做实时传输作用
		$real_arr=array();
		//单条写入
		$ind=0;
		for($rowIndex=$start+1;$rowIndex<=$length;$rowIndex++){        //循环读取每个单元格的内容。注意行从1开始，列从A开始
			//判断公证事项是否存在
			$notary_matter=$currentSheet->getCell('J'.$rowIndex)->getValue();
//			$notary_matter_id=$this->check_notary_matter($notary_matter);
//			if($notary_matter_id==FALSE){
//				$this->db->trans_rollback();
//				//删除导入的批次
////				$w['lot_number']=$number;
////				$this->archive_model->delete_archive($w);
////				$err_data['error_data']='批量上传目录信息失败，本次导入数据已全部清空，出错行数是 '.$rowIndex.' ，首行内容是 '.$currentSheet->getCell('A'.$rowIndex)->getValue();
//				$err_data['error_data']='批量上传目录信息失败，出错行数是 '.$rowIndex.' ，首行内容是 '.$currentSheet->getCell('A'.$rowIndex)->getValue();
//				json_return('error','批量导入失败',$err_data);
//			}
			//判断案卷是否存在
			$isnullwhere['new_number']=$currentSheet->getCell('A'.$rowIndex)->getValue();
			$isnullres=$this->archive_model->get_archive_detail($isnullwhere,'id');
//原本带旧案卷号的excel数据
//			$data=array(
//				"new_number"=>$currentSheet->getCell('A'.$rowIndex)->getValue(),
//				"old_number"=>$currentSheet->getCell('B'.$rowIndex)->getValue(),
//				"word_no"=>$currentSheet->getCell('C'.$rowIndex)->getValue(),
//				"category_id"=>$currentSheet->getCell('H'.$rowIndex)->getValue(),
//				"notary_matter_id"=>$notary_matter_id,
////				"litigant_type"=>'',
////				"litigant_org"=>'',
//				"litigant_name"=>$currentSheet->getCell('N'.$rowIndex)->getValue(),
//				"litigant_card"=>$currentSheet->getCell('O'.$rowIndex)->getValue(),
////				"litigant_sex"=>'',
////				"litigant_date"=>'',
//				"undertaker"=>$currentSheet->getCell('L'.$rowIndex)->getValue(),
//				"receive_time"=>strtotime($currentSheet->getCell('P'.$rowIndex)->getValue()),
//				"receive_year"=>$currentSheet->getCell('F'.$rowIndex)->getValue(),
//				"archive_time"=>strtotime($currentSheet->getCell('R'.$rowIndex)->getValue()),
//				"greffier"=>$currentSheet->getCell('M'.$rowIndex)->getValue(),
////				"notarial_reason"=>'',
//				"department_id"=>$department_id,
//				"over_time"=>strtotime($currentSheet->getCell('Q'.$rowIndex)->getValue()),
//				"storage_time_id"=>$currentSheet->getCell('S'.$rowIndex)->getValue(),
//				"box_number"=>$currentSheet->getCell('D'.$rowIndex)->getValue(),
//				"volume_number"=>$currentSheet->getCell('E'.$rowIndex)->getValue(),
//				"first_page"=>$currentSheet->getCell('X'.$rowIndex)->getValue(),
//				"jian_number"=>$currentSheet->getCell('V'.$rowIndex)->getValue(),
//				"page"=>$currentSheet->getCell('W'.$rowIndex)->getValue(),
////				"pdf_num"=>'',
//				"identifier"=>$currentSheet->getCell('I'.$rowIndex)->getValue(),
//				"heavy_number"=>$currentSheet->getCell('J'.$rowIndex)->getValue(),
//				"fonds_number"=>$currentSheet->getCell('T'.$rowIndex)->getValue(),
//				"directory_number"=>$currentSheet->getCell('U'.$rowIndex)->getValue(),
//				"lot_number"=>$number,
//				'remark'=>$currentSheet->getCell('Y'.$rowIndex)->getValue(),
//				'guid'=>$currentSheet->getCell('Z'.$rowIndex)->getValue(),
//				"update_time"=>time(),
//				"create_time"=>time()
//			);
			$data=array(
				"new_number"=>$currentSheet->getCell('A'.$rowIndex)->getValue(),
//				"old_number"=>$currentSheet->getCell('B'.$rowIndex)->getValue(),
				"word_no"=>$currentSheet->getCell('B'.$rowIndex)->getValue(),
				"category_id"=>$currentSheet->getCell('G'.$rowIndex)->getValue(),
				"notary_matter_name"=>$notary_matter,
//				"litigant_type"=>'',
//				"litigant_org"=>'',
				"litigant_name"=>$currentSheet->getCell('M'.$rowIndex)->getValue(),
				"litigant_card"=>$currentSheet->getCell('N'.$rowIndex)->getValue(),
//				"litigant_sex"=>'',
//				"litigant_date"=>'',
				"undertaker"=>$currentSheet->getCell('K'.$rowIndex)->getValue(),
				"receive_time"=>strtotime($currentSheet->getCell('O'.$rowIndex)->getValue()),
				"receive_year"=>$currentSheet->getCell('E'.$rowIndex)->getValue(),
				"archive_time"=>strtotime($currentSheet->getCell('Q'.$rowIndex)->getValue()),
				"greffier"=>$currentSheet->getCell('L'.$rowIndex)->getValue(),
//				"notarial_reason"=>'',
				"department_id"=>$department_id,
				"over_time"=>strtotime($currentSheet->getCell('P'.$rowIndex)->getValue()),
				"storage_time_id"=>$currentSheet->getCell('R'.$rowIndex)->getValue(),
				"box_number"=>$currentSheet->getCell('C'.$rowIndex)->getValue(),
				"volume_number"=>$currentSheet->getCell('D'.$rowIndex)->getValue(),
				"first_page"=>$currentSheet->getCell('W'.$rowIndex)->getValue(),
				"jian_number"=>$currentSheet->getCell('U'.$rowIndex)->getValue(),
				"page"=>$currentSheet->getCell('V'.$rowIndex)->getValue(),
//				"pdf_num"=>'',
				"identifier"=>$currentSheet->getCell('H'.$rowIndex)->getValue(),
				"heavy_number"=>$currentSheet->getCell('I'.$rowIndex)->getValue(),
				"fonds_number"=>$currentSheet->getCell('S'.$rowIndex)->getValue(),
				"directory_number"=>$currentSheet->getCell('T'.$rowIndex)->getValue(),
				'remark'=>$currentSheet->getCell('X'.$rowIndex)->getValue(),
				'guid'=>$currentSheet->getCell('Y'.$rowIndex)->getValue(),
				"update_time"=>time(),
				"create_time"=>time()
			);

			if($isnullres==NULL){
				//不存在写入
				$res=$this->archive_model->add_archive_one($data);
				$real_arr[]=$data['category_id'];
			}else{
				//存在更新
				unset($data['create_time']);
				$update_where['id']=$isnullres['id'];
				$res=$this->archive_model->update_archive_one($update_where,$data);
			}

//			p($res);
			if ($this->db->trans_status() === FALSE || $this->db->affected_rows()==0||$res==false)
			{
				$this->db->trans_rollback();
				//删除导入的批次
//				$w['lot_number']=$number;
//				$this->archive_model->delete_archive($w);
//				$err_data['error_data']='批量上传案卷信息失败，本次导入数据已全部清空，出错行数是 '.$rowIndex.' ，首行内容是 '.$currentSheet->getCell('A'.$rowIndex)->getValue();
				$err_data['error_data']='批量上传案卷信息失败，出错行数是 '.$rowIndex.' ，首行内容是 '.$currentSheet->getCell('A'.$rowIndex)->getValue();
				json_return('error','批量导入失败',$err_data);
			}
			$ind++;
			if($ind==$chunkSize){
				//写入
//				$res=$this->archive_model->add_archive_pdf($data);
//				if($res==FALSE){
//					json_return('error','批量导入失败');
//				}
//				$this->db->trans_commit();
//				$d['len']=$length;
//				$d['percent']=($start-1+$chunkSize)/($length-1);
//				json_return('continue','',$d);
				break;
			}
		}
		if($rowIndex>$length){
			$status='ok';
		}else{
			$status='continue';
		}

		$this->db->trans_commit();

		$d['len']=$length;
		$d['real_time']=$real_arr;
		$d['percent']=($start-1+$ind)/($length-1);
		json_return($status,'',$d);
	}

	/*
	 * 获取excel长度
	 * */
	public function get_excel_length(){
		$file=$_POST['file'];
//		$file='./uploads/excel/anjuan_20170525003922727539.xlsx';
		$this->load->library('Classes/PHPExcel.php');
		//没有计算到长度,获取长度
		$inputFileType = PHPExcel_IOFactory::identify($file);
		$objReader = PHPExcel_IOFactory::createReader($inputFileType);
		$objPHPExcel = $objReader->load($file);
		$currentSheet = $objPHPExcel->getSheet(0);
		$allRow = $currentSheet->getHighestRow();

		$d['len']=$allRow;
		json_return('ok','',$d);
	}

	/*
	 * 目录写入
	 * */
	public function mulu_insert(){
		$file=$_POST['file'];
		$start=$_POST['start'];
		$department_id=$_POST['department_id'];
		$length=$_POST['length'];//长度
		$this->load->library('Classes/PHPExcel.php');

		$inputFileType = PHPExcel_IOFactory::identify($file);
		$objReader = PHPExcel_IOFactory::createReader($inputFileType);
		$chunkSize = 50;    // 定义每块读去的行数,每次读取50条
		// 就可在一个循环中，多次读去块，而不用一次性将整个Excel表读入到内存中
		$chunkFilter = new chunkReadFilter($start+1, $chunkSize);
		$objReader->setReadFilter($chunkFilter); // 设置实例化的过滤器对象
		$objPHPExcel = $objReader->load($file);
		$currentSheet = $objPHPExcel->getSheet(0);
//		$allRow = $currentSheet->getHighestRow();
		// 开始读取每行数据，并插入到数据库
//		$d=$objPHPExcel->getActiveSheet()->toArray();

		$this->db->trans_begin();//开启事务

		//单条写入
		$ind=0;
		$real_arr=array();
		for($rowIndex=$start+1;$rowIndex<=$length;$rowIndex++){        //循环读取每个单元格的内容。注意行从1开始，列从A开始
			//查询父表数据是否存在.先获取父表的new_number
			$child_new_number=$currentSheet->getCell('A'.$rowIndex)->getValue();
			$new_number=substr($child_new_number,0,strrpos($child_new_number,'-'));
			//查询父表是否存在
			$parent_where['new_number']=$new_number;
			$parent_res=$this->archive_model->get_archive_detail($parent_where,'id,category_id,department_id');
			if($parent_res==NULL){
				$err_data['error_data']='批量上传目录信息失败，尚未导入主表数据，出错行数是 '.$rowIndex.' ，首行内容是 '.$currentSheet->getCell('A'.$rowIndex)->getValue();
				json_return('error','批量导入失败',$err_data);
			}

			//判断数据是否存在
			$isnullwhere['new_number']=$currentSheet->getCell('A'.$rowIndex)->getValue();
			$isnull_res=$this->archive_model->get_archive_pdf_one($isnullwhere,'id');
			$data=array(
				'department_id'=>$parent_res['department_id'],
				'archive_id'=>$parent_res['id'],
				'new_number'=>$currentSheet->getCell('A'.$rowIndex)->getValue(),
//				'old_number'=>$currentSheet->getCell('B'.$rowIndex)->getValue(),
				'file_name'=>$currentSheet->getCell('B'.$rowIndex)->getValue(),
				'person_liable'=>$currentSheet->getCell('C'.$rowIndex)->getValue(),
				'page'=>$currentSheet->getCell('D'.$rowIndex)->getValue(),
				'start_page'=>$currentSheet->getCell('E'.$rowIndex)->getValue(),
				'end_page'=>$currentSheet->getCell('F'.$rowIndex)->getValue(),
				'order_id'=>$currentSheet->getCell('G'.$rowIndex)->getValue(),
				'remark'=>$currentSheet->getCell('H'.$rowIndex)->getValue(),
				'update_time'=>time(),
				'create_time'=>time()
			);
			if($isnull_res==NULL){
				//数据不存在.写入
				$res=$this->archive_model->add_archive_pdf_one($data);
				$real_arr[]=array($parent_res['category_id'],$data['page']);
			}else{
				//数据存在,更新
				unset($data['create_time']);
				$updatewhere['id']=$isnull_res['id'];
				$res=$this->archive_model->update_archive_pdf_one($updatewhere,$data);
			}


			if ($this->db->trans_status() === FALSE || $this->db->affected_rows()==0||$res==false)
			{
				$this->db->trans_rollback();
				//删除导入的批次
//				$w['lot_number']=$number;
//				$this->archive_model->delete_archive_pdf($w);
//				$err_data['error_data']='批量上传目录信息失败，本次导入数据已全部清空，出错行数是 '.$rowIndex.' ，首行内容是 '.$currentSheet->getCell('A'.$rowIndex)->getValue();
				$err_data['error_data']='批量上传目录信息失败，出错行数是 '.$rowIndex.' ，首行内容是 '.$currentSheet->getCell('A'.$rowIndex)->getValue();
				json_return('error','批量导入失败',$err_data);
			}
			$ind++;
			if($ind==$chunkSize){
				//写入
//				$res=$this->archive_model->add_archive_pdf($data);
//				if($res==FALSE){
//					json_return('error','批量导入失败');
//				}
//				$this->db->trans_commit();
//				$d['len']=$length;
//				$d['percent']=($start-1+$chunkSize)/($length-1);
//				json_return('continue','',$d);
				break;
			}
		}
		if($rowIndex>$length){
			$status='ok';
		}else{
			$status='continue';
		}

		$this->db->trans_commit();
//		if(count($data)!=0){
//			$res=$this->archive_model->add_archive_pdf($data);
//			if($res==FALSE){
//				json_return('error','批量导入失败');
//			}
//		}
		$d['len']=$length;
		$d['real_time']=$real_arr;
		$d['percent']=($start-1+$ind)/($length-1);
		json_return($status,'',$d);
	}



	private function conv2utf8($str){
		return iconv('gb2312', 'utf-8', $str);
	}

	/*
	 * 诚信数据库
	 * */
	public function cx_archive(){
		$this->load->view('admin/common/header');
		$this->load->view('admin/archive/cx_archive');
	}

	/*
     * 诚信数据库查询json数据
     * */
	public function cx_archive_index_json(){
		$where=array();
		$like=array();
		$page=isset($_POST['page'])?$_POST['page']:1;
		$rows=isset($_POST['rows'])?$_POST['rows']:50;
		$department_id=isset($_POST['department_id'])?$_POST['department_id']:0;
		$greffier=isset($_POST['greffier'])?$_POST['greffier']:'';
		$undertaker=isset($_POST['undertaker'])?$_POST['undertaker']:'';
		$word_no=isset($_POST['word_no'])?$_POST['word_no']:'';
		$litigant_name=isset($_POST['litigant_name'])?$_POST['litigant_name']:'';
		$litigant_card=isset($_POST['litigant_card'])?$_POST['litigant_card']:'';

		$receive_time_chk=isset($_POST['receive_time_chk'])?$_POST['receive_time_chk']:false;
		$receive_time_from=isset($_POST['receive_time_from'])?$_POST['receive_time_from']:'';
		$receive_time_to=isset($_POST['receive_time_to'])?$_POST['receive_time_to']:'';

		$over_time_chk=isset($_POST['over_time_chk'])?$_POST['over_time_chk']:false;
		$over_time_from=isset($_POST['over_time_from'])?$_POST['over_time_from']:'';
		$over_time_to=isset($_POST['over_time_to'])?$_POST['over_time_to']:'';
		if($department_id==-1){
			echo NULL;
		}
		if($department_id!=0){
			$where['a.department_id']=$department_id;
		}
		if($greffier!=''){
			$like['a.greffier']=$greffier;
		}
		if($undertaker!=''){
			$like['a.undertaker']=$undertaker;
		}
		if($word_no!=''){
			$like['a.word_no']=$word_no;
		}
		if($litigant_name!=''){
			$like['a.litigant_name']=$litigant_name;
		}
		if($litigant_card!=''){
			$where['a.litigant_card']=$litigant_card;
		}
		//日期判断
		if($receive_time_chk=='true'){
			if($receive_time_from!=''){
				$where['a.receive_time >=']=strtotime($receive_time_from);
			}
			if($receive_time_to!=''){
				$where['a.receive_time <=']=strtotime($receive_time_to);
			}
		}
		if($over_time_chk=='true'){
			if($over_time_from!=''){
				$where['a.over_time >=']=strtotime($over_time_from);
			}
			if($over_time_to!=''){
				$where['a.over_time <=']=strtotime($over_time_to);
			}
		}
		$where_in=array('保证','还款','抵押','借款','执行');
		$res=$this->archive_model->get_archive_list($where,$rows,$page,'id desc',$like,$where_in);
		echo json_encode($res);
	}

	/*
	 * 获取附件的pdf文件
	 * */
	public function get_archive_pdf_json(){
		$archive=$_POST['id'];
		if($archive==0){
			echo NULL;
		}else{
			$where['archive_id']=$archive;
			$res=$this->archive_attachment_pdf_model->get_pdf($where,'id,department_id,new_number,file_name');
			if($res==NULL){
				echo NULL;
			}else{
				echo json_encode($res);
			}
		}
	}

	/*
	 * 删除案卷
	 * */
	public function delete_archive(){
		$id=$_POST['id'];
		//删除案卷
		$this->db->trans_begin();
		$where['id']=$id;
		$this->archive_model->delete_archive($where);
		if ($this->db->trans_status() === FALSE||$this->db->affected_rows()==0)
		{
			$this->db->trans_rollback();
			json_return('error','删除案卷失败');
		}
		else
		{
			//删除目录
			unset($where);
			$where['archive_id']=$id;
			$res=$this->archive_model->delete_archive_pdf($where);
			if ($this->db->trans_status() === FALSE||$this->db->affected_rows()==0)
			{
				$this->db->trans_rollback();
				json_return('error','删除案卷失败');
			}else{
				$this->db->trans_commit();
				json_return('ok','删除案卷成功');
			}
		}
	}

	/*
	 * 上传pdf文件
	 * */
	public function uploads_pdf(){
		$department_id=$_POST['department_id'];
		$config['upload_path']      ='.'.$this->path.$department_id.'/';
//		p($config['upload_path']);
		$config['allowed_types']    = 'pdf';
		$config['max_size']     = 1024*10;
		$config['overwrite']     = TRUE;

		$this->load->library('upload', $config);

		if ( ! $this->upload->do_upload('pdf_file'))
		{
			$error = $this->upload->display_errors();

			json_return('error',$error);
		}
		else
		{
			$d=$this->upload->data();
//			$data = array('filepath' => $config['upload_path'].'/'.$d['file_name']);
			//只返回文件大小
			json_return('ok','');
		}
	}
}



